package com.book.controller;

import com.book.common.Result;
import com.book.dto.LoginRequest;
import com.book.service.UserService;
import com.book.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    /**
     * 生成验证码
     */
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletResponse response) throws IOException {
        // 生成验证码
        CaptchaUtil.CaptchaResult captchaResult = CaptchaUtil.generateCaptcha();
        
        // 生成UUID作为key
        String captchaKey = UUID.randomUUID().toString();
        
        // 将验证码答案存储到Redis，5分钟过期
        redisTemplate.opsForValue().set("captcha:" + captchaKey, captchaResult.getCode(), 5, TimeUnit.MINUTES);
        
        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Captcha-Key", captchaKey);
        
        // 输出图片
        ImageIO.write(captchaResult.getImage(), "PNG", response.getOutputStream());
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.login(loginRequest);
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("username", loginRequest.getUsername());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody LoginRequest loginRequest) {
        try {
            // 这里可以添加用户注册逻辑
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
} 